package com.unlcn.ils.wms.backend.service.inspectApp.impl;

import cn.huiyunche.commons.constant.QiniuConstant;
import cn.huiyunche.commons.domain.PageVo;
import cn.huiyunche.commons.domain.QiniuResponseVO;
import cn.huiyunche.commons.exception.BusinessException;
import cn.huiyunche.commons.utils.HttpRequestUtil;
import cn.huiyunche.commons.utils.QiniuUtil;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.unlcn.ils.wms.backend.bo.inspectAppBO.TmsInboundInspectBO;
import com.unlcn.ils.wms.backend.bo.inspectAppBO.TmsInboundMoveCarBO;
import com.unlcn.ils.wms.backend.bo.inspectAppBO.WmsInboundConfirmBO;
import com.unlcn.ils.wms.backend.bo.sys.UserBO;
import com.unlcn.ils.wms.backend.enums.*;
import com.unlcn.ils.wms.backend.service.inspectApp.TmsInboundService;
import com.unlcn.ils.wms.backend.service.sys.UserService;
import com.unlcn.ils.wms.backend.util.DateUtils;
import com.unlcn.ils.wms.backend.util.QRCodeUtils;
import com.unlcn.ils.wms.backend.util.SnowflakeIdWorker;
import com.unlcn.ils.wms.backend.util.jpush.JpushClientUtils;
import com.unlcn.ils.wms.base.dto.WmsInboundInspectDTO;
import com.unlcn.ils.wms.base.dto.WmsInboundNotMoveCarDTO;
import com.unlcn.ils.wms.base.dto.WmsWarehouseNoticeHeadDTO;
import com.unlcn.ils.wms.base.dto.WmsWaybillInfoParamDTO;
import com.unlcn.ils.wms.base.mapper.extmapper.WmsTmsOrderExtMapper;
import com.unlcn.ils.wms.base.mapper.extmapper.WmsWarehouseNoticeExtMapper;
import com.unlcn.ils.wms.base.mapper.inbound.*;
import com.unlcn.ils.wms.base.mapper.inspectApp.TmsInboundLogMapper;
import com.unlcn.ils.wms.base.mapper.inspectApp.TmsInboundQrcodeAttachsMapper;
import com.unlcn.ils.wms.base.mapper.inspectApp.TmsInspectExcpTypeMapper;
import com.unlcn.ils.wms.base.mapper.inspectApp.WmsInboundInspectExpandMapper;
import com.unlcn.ils.wms.base.mapper.junmadcs.WmsOutOfStorageMapper;
import com.unlcn.ils.wms.base.mapper.stock.WmsInventoryLocationMapper;
import com.unlcn.ils.wms.base.mapper.stock.WmsInventoryMapper;
import com.unlcn.ils.wms.base.mapper.stock.WmsWarehouseMapper;
import com.unlcn.ils.wms.base.mapper.sys.SysUserMapper;
import com.unlcn.ils.wms.base.model.inbound.*;
import com.unlcn.ils.wms.base.model.inspectApp.TmsInboundLog;
import com.unlcn.ils.wms.base.model.inspectApp.TmsInboundQrcodeAttachs;
import com.unlcn.ils.wms.base.model.inspectApp.TmsInboundQrcodeAttachsExample;
import com.unlcn.ils.wms.base.model.inspectApp.TmsInspectExcpType;
import com.unlcn.ils.wms.base.model.junmadcs.WmsOutOfStorage;
import com.unlcn.ils.wms.base.model.stock.WmsInventory;
import com.unlcn.ils.wms.base.model.stock.WmsInventoryLocation;
import com.unlcn.ils.wms.base.model.stock.WmsWarehouse;
import com.unlcn.ils.wms.base.model.stock.WmsWarehouseExample;
import com.unlcn.ils.wms.base.model.sys.SysUser;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 入库业务
 */
@Service
public class TmsInboundServiceImpl implements TmsInboundService {
    private Logger logger = LoggerFactory.getLogger(TmsInboundServiceImpl.class);

    private static final int VIN_LENGTH = 17;

    private static final int MIN_LENGTH = 6;

    private static final String TYPE_INBOUND = "1002";//入库收货质检和入库确认推送类别

    @Value("${tms.pickup.host.url}")
    private String propertyUrl;

    @Value("${tms.pickup.host.timeout}")
    private String propertyTime;

    @Value("${tms.encode.key}")
    private String propertyKey;

    @Autowired
    private TmsInboundQrcodeAttachsMapper tmsInboundQrcodeAttachsMapper;

    @Autowired
    private TmsInboundLogMapper tmsInboundLogMapper;

    @Autowired
    private WmsInboundInspectExpandMapper wmsInboundInspectExpandMapper;

    @Autowired
    private WmsInboundOrderMapper wmsInboundOrderMapper;

    @Autowired
    private WmsInboundOrderDetailMapper wmsInboundOrderDetailMapper;

    @Autowired
    private WmsInventoryLocationMapper wmsInventoryLocationMapper;

    @Autowired
    private WmsInventoryMapper wmsInventoryMapper;

    @Autowired
    private WmsInboundAllocationMapper wmsInboundAllocationMapper;

    @Autowired
    private WmsWarehouseMapper wmswarehousemapper;

    @Autowired
    private UserService userService;

    @Autowired
    private WmsOutOfStorageMapper wmsOutOfStorageMapper;

    @Autowired
    private TmsInspectExcpTypeMapper tmsInspectExcpTypeMapper;

    @Autowired
    private SysUserMapper sysUserMapper;


    private WmsTmsOrderExtMapper wmsTmsOrderExtMapper;
    private WmsTmsLogMapper wmsTmsLogMapper;
    private WmsTmsOrderMapper wmsTmsOrderMapper;

    @Autowired
    public void setWmsTmsOrderMapper(WmsTmsOrderMapper wmsTmsOrderMapper) {
        this.wmsTmsOrderMapper = wmsTmsOrderMapper;
    }

    @Autowired
    public void setWmsTmsLogMapper(WmsTmsLogMapper wmsTmsLogMapper) {
        this.wmsTmsLogMapper = wmsTmsLogMapper;
    }

    @Autowired
    public void setWmsTmsOrderExtMapper(WmsTmsOrderExtMapper wmsTmsOrderExtMapper) {
        this.wmsTmsOrderExtMapper = wmsTmsOrderExtMapper;
    }


    /**
     * 查询运单信息
     * <p>
     * 更新增加新需求:重庆库车架号模糊匹配
     * </p>
     *
     * @param paramDTO 车架号
     * @return 返回值
     * @throws Exception 异常
     */
    @Override
    public Map<String, Object> getInboundInspectInfo(WmsWaybillInfoParamDTO paramDTO) throws Exception {
        logger.info("TmsInboundServiceImpl.getInboundInspectInfo params:{}", JSONObject.toJSONString(paramDTO));
        if (Objects.equals(paramDTO, null))
            throw new BusinessException("参数不能为空!");
        String whCode = paramDTO.getWhCode();
        String vin = paramDTO.getVin();
        if (StringUtils.isBlank(whCode))
            throw new BusinessException("仓库code 不能为空!");
        if (StringUtils.isBlank(vin))
            throw new BusinessException("车架号不能为空!");
        if (vin.endsWith("\n"))
            vin = vin.replaceAll("\n", "");
        // 只返回相应的车架号信息
        ArrayList<TmsInboundInspectBO> bos = Lists.newArrayList();
        Map<String, Object> resultMap = Maps.newHashMap();
        Map<String, Object> paramMap = Maps.newHashMap();
        paramMap.put("status_10", WmsInboundStatusEnum.WMS_INBOUND_CREATE.getValue());//用于过滤入库表里车架号多条的记录
        paramMap.put("status_20", WmsInboundStatusEnum.WMS_INBOUND_WAIT_INBOUND.getValue());
        paramMap.put("notDel", DeleteFlagEnum.NORMAL.getValue());
        List<WmsInboundInspectDTO> dtoList = null;
        if (vin.length() != VIN_LENGTH) {
            //模糊查询 重庆库功能--2018-1-30 新增模糊查询功能
            if (vin.length() < MIN_LENGTH) {
                throw new BusinessException("请输入6位及以上长度的数据");
            }
            if (!WhCodeEnum.UNLCN_XN_CQ.getValue().equals(whCode)) {
                throw new BusinessException("该仓库不支持此操作");
            }
            resultMap.put("searchType", WmsSysSourceEnum.LIKE.getValue());
            paramMap.put("vin", "%" + vin + "%");
            dtoList = wmsInboundInspectExpandMapper.selectNotMoveByVinLikeParamForCQ(paramMap);
            //判断模糊匹配到的数据条目
            if (CollectionUtils.isEmpty(dtoList))
                throw new BusinessException("未查询到对应车辆:" + vin + "车辆入库信息");
            if (CollectionUtils.isNotEmpty(dtoList)) {
                dtoList.stream().filter(v -> !Objects.equals(v, null)
                        && StringUtils.isNotBlank(v.getVin()))
                        .forEach(v -> {
                            TmsInboundInspectBO bo = new TmsInboundInspectBO();
                            bo.setVin(v.getVin());
                            bos.add(bo);
                        });
            }
            resultMap.put("bos", bos);
            resultMap.put("searchType", WmsSysSourceEnum.LIKE.getValue());

        } else {
            //传入的是车架号
            paramMap.put("vin", vin);
            dtoList = wmsInboundInspectExpandMapper.selectNotMoveCarInfoByVinParam(paramMap);
            if (CollectionUtils.isEmpty(dtoList)) {
                throw new BusinessException("未查询到对应车辆:" + vin + "车辆入库信息");
            }
            WmsInboundInspectDTO inspectDTO = updateInspectDTO(dtoList);
            bos.add(getWmsWaybillInfoBO(inspectDTO));
            resultMap.put("searchType", WmsSysSourceEnum.ACCURATE.getValue());
            resultMap.put("bos", bos);
        }
        return resultMap;
    }

    /**
     * 移库申请数据回显
     *
     * @param inspectDTO 参数封装
     * @return 返回值
     */
    private TmsInboundInspectBO getWmsWaybillInfoBO(WmsInboundInspectDTO inspectDTO) {
        if (inspectDTO != null) {
            TmsInboundInspectBO inspectBO = new TmsInboundInspectBO();
            inspectBO.setInspectStatusValue(inspectDTO.getInspectStatus());
            TmsInspectStatusEnum statusEnum = TmsInspectStatusEnum.getByValue(inspectDTO.getInspectStatus());
            if (statusEnum != null) {
                inspectBO.setInspectStatusText(statusEnum.getText());
            }
            inspectBO.setWaybillCode(inspectDTO.getWaybillCode());
            inspectBO.setGmtCreate(inspectDTO.getGenerateTime());
            inspectBO.setGmtUpdate(inspectDTO.getInspectTime());
            inspectBO.setId(inspectDTO.getId());
            inspectBO.setStyle(inspectDTO.getVehicle());
            inspectBO.setStyleDesc(inspectDTO.getVehicleDesc());
            inspectBO.setVin(inspectDTO.getVin());
            inspectBO.setEngine(inspectDTO.getEngine());
            return inspectBO;
        }
        return null;
    }

    /**
     * 查询运单信息
     *
     * @param wmsInboundInspectDTOS 参数
     * @return 返回值
     */
    private WmsInboundInspectDTO updateInspectDTO(List<WmsInboundInspectDTO> wmsInboundInspectDTOS) {
        WmsInboundInspectDTO wmsInboundInspectDTO = wmsInboundInspectDTOS.get(0);
        //--一条数据
        if (wmsInboundInspectDTOS.size() > 1) {
            throw new BusinessException("数据异常!该车架号:" + wmsInboundInspectDTO.getVin() + "数据库存在多条数据");
        }
        //校验状态
        if (Objects.equals(wmsInboundInspectDTO.getInspectStatus(), TmsInspectStatusEnum.WAYBILL_INIT.getValue())) {
            throw new BusinessException("请先进行验车操作");
        }
        if (Objects.equals(wmsInboundInspectDTO.getInspectStatus(), TmsInspectStatusEnum.WAYBILL_EXCP.getValue())) {
            throw new BusinessException("请先进行验车登记操作!");
        }
        //君马库
        if (WhCodeEnum.JM_XY.getValue().equals(wmsInboundInspectDTO.getWhCode())
                || WhCodeEnum.JM_CS.getValue().equals(wmsInboundInspectDTO.getWhCode())) {
            if (Objects.equals(wmsInboundInspectDTO.getInspectStatus(), TmsInspectStatusEnum.WAYBILL_CONFIRM_EXCP.getValue())) {
                //君马库可以多条，但是要过滤掉非质损异常
                Integer excpType = wmsInboundInspectDTO.getExcpType();
                TmsInspectExcpType tmsInspectExcpType = tmsInspectExcpTypeMapper.selectByPrimaryKey(excpType);
                if (Objects.equals(tmsInspectExcpType, null)) {
                    throw new BusinessException("未查询到对应的异常分类!");
                }
                String typeCode = tmsInspectExcpType.getTypeCode();
                if (!Objects.equals(WmsInspectExcpTypeEnum.TYPE_MISS.getCode(), typeCode)) {
                    //就不能进行入库操作,不进行显示
                    throw new BusinessException("该车架号:" + wmsInboundInspectDTO.getVin() + "的异常类型不允许该操作!");
                }
            }
        }
        return wmsInboundInspectDTO;
    }

    /**
     * 移车申请,绑定司机信息
     *
     * @param inspectId 运单
     * @param driverId  司机id
     * @return 返回值
     */
    @Override
    public TmsInboundMoveCarBO updateMoveCar(String whCode, Long inspectId, String driverId) throws Exception {
        logger.info("TmsInboundServiceImpl.moveCar params:{}", inspectId, driverId);
        if (Objects.equals(inspectId, null)) {
            throw new BusinessException("验车id不能为空!");
        }
        if (StringUtils.isBlank(driverId)) {
            throw new BusinessException("用户Id不能为空!");
        }
        if (StringUtils.isBlank(whCode)) {
            throw new BusinessException("仓库code不能为空!");
        }
        try {
            WmsInboundOrder wmsInboundOrder = wmsInboundOrderMapper.selectByPrimaryKey(inspectId);
            if (!Objects.equals(wmsInboundOrder, null)) {
                if (Objects.equals(wmsInboundOrder.getInspectStatus(), TmsInspectStatusEnum.WAYBILL_INIT.getValue())) {
                    throw new BusinessException("请先进行验车!");
                }
                if (Objects.equals(wmsInboundOrder.getInspectStatus(), TmsInspectStatusEnum.WAYBILL_EXCP.getValue())) {
                    throw new BusinessException("请进行验车登记操作");
                }
                if (String.valueOf(WmsInboundStatusEnum.WMS_INBOUND_FINISH.getValue()).equals(wmsInboundOrder.getOdStatus())) {
                    throw new BusinessException("该车已入库不能再进行该操作!");
                }

                wmsInboundOrder.setOdSupplierId(driverId);//绑定司机

                wmsInboundOrderMapper.updateByPrimaryKeySelective(wmsInboundOrder);

                WmsInboundOrderDetailExample detailExample = new WmsInboundOrderDetailExample();
                WmsInboundOrderDetailExample.Criteria criteria = detailExample.createCriteria();
                criteria.andOddOdIdEqualTo(wmsInboundOrder.getOdId());
                List<WmsInboundOrderDetail> wmsInboundOrderDetails = wmsInboundOrderDetailMapper.selectByExample(detailExample);
                if (CollectionUtils.isNotEmpty(wmsInboundOrderDetails)) {
                    WmsInboundOrderDetail orderDetail = wmsInboundOrderDetails.get(0);
                    //获取库位信息及入库状态
                    WmsInboundAllocationExample allocationExample = new WmsInboundAllocationExample();
                    WmsInboundAllocationExample.Criteria allocationExampleCriteria = allocationExample.createCriteria();
                    allocationExampleCriteria.andAlVinEqualTo(orderDetail.getOddVin());
                    allocationExampleCriteria.andIsDeletedNotEqualTo(DeleteFlagEnum.DELETED.getValue());
                    List<WmsInboundAllocation> wmsInboundAllocations = wmsInboundAllocationMapper.selectByExample(allocationExample);

                    TmsInboundMoveCarBO moveCarBO = new TmsInboundMoveCarBO();
                    if (CollectionUtils.isNotEmpty(wmsInboundAllocations)) {
                        WmsInboundAllocation wmsInboundAllocation = wmsInboundAllocations.get(0);
                        //获取入库的状态
                        WmsInboundStatusEnum statusEnum = WmsInboundStatusEnum.getByValue(Integer.valueOf(wmsInboundOrder.getOdStatus()));
                        if (statusEnum != null) {
                            moveCarBO.setInboundStatusValue(statusEnum.getValue());
                            moveCarBO.setInboundStatusText(statusEnum.getText());
                            moveCarBO.setWarehousingLocation(wmsInboundAllocation.getAlSourceLocCode());
                        }
                    } else {
                        //默认给出待入库状态
                        moveCarBO.setInboundStatusValue(WmsInboundInventoryEnum.INIT.getValue());
                        moveCarBO.setInboundStatusText(WmsInboundInventoryEnum.INIT.getText());
                        moveCarBO.setWarehousingLocation(null);
                    }
                    //获取已存在的二维码图片
                    TmsInboundQrcodeAttachsExample attachsExample = new TmsInboundQrcodeAttachsExample();
                    TmsInboundQrcodeAttachsExample.Criteria attachsExampleCriteria = attachsExample.createCriteria();
                    attachsExampleCriteria.andDelFlagNotEqualTo(false);
                    attachsExampleCriteria.andInboundIdEqualTo(wmsInboundOrder.getOdId());
                    List<TmsInboundQrcodeAttachs> tmsInboundQrcodeAttachs = tmsInboundQrcodeAttachsMapper.selectByExample(attachsExample);
                    if (CollectionUtils.isNotEmpty(tmsInboundQrcodeAttachs)) {
                        //已经存在获取downloadurl
                        TmsInboundQrcodeAttachs qrcodeAttachs = tmsInboundQrcodeAttachs.get(0);
                        String downloadURL = QiniuUtil.generateDownloadURL(QiniuConstant.QINIU_DOWNLOAD_ADDRESS, qrcodeAttachs.getPicKey(), "", null, null);
                        moveCarBO.setPicUrl(downloadURL);
                    } else {
                        //1.根据vin生成二维码,上传图片至七牛获取链接插入图片key到移库申请表;
                        String dowloadUrl = generateQRCode(wmsInboundOrder, orderDetail.getOddVin());
                        moveCarBO.setPicUrl(dowloadUrl);
                    }
                    moveCarBO.setWarhousingDriverId(driverId);
                    moveCarBO.setVin(orderDetail.getOddVin());
                    return moveCarBO;
                }
                //}
            }
            //插入入库申请日志
            TmsInboundLog log = new TmsInboundLog();
            log.setGmtCreate(new Date());
            log.setGmtUpdate(new Date());
            log.setInboundId(wmsInboundOrder.getOdId());
            log.setMsg("移库申请成功!");
            log.setUserId(driverId);
            tmsInboundLogMapper.insertSelective(log);
        } catch (Exception e) {
            logger.error("TmsInboundServiceImpl.moveCar params:{}", e.getMessage());
            throw new BusinessException("移库申请异常!" + e.getMessage());
        }
        return null;
    }


    /**
     * 生成二维码图片,保存图片信息
     *
     * @param wmsInboundOrder 订单信息
     * @param vin             车架号
     */
    private String generateQRCode(WmsInboundOrder wmsInboundOrder, String vin) throws Exception {
        ByteArrayOutputStream byteArrayOutputStream = null;
        try {
            byteArrayOutputStream = new ByteArrayOutputStream();
            //生成不带logo到指定输出流
            QRCodeUtils.encode(vin, byteArrayOutputStream);
            QiniuResponseVO upload = QiniuUtil.upload(byteArrayOutputStream.toByteArray(), null);
            String key = upload.getKey();
            String downloadURL = QiniuUtil.generateDownloadURL(QiniuConstant.QINIU_DOWNLOAD_ADDRESS, key, "", null, null);
            //保存信息到入库二维码图片表
            TmsInboundQrcodeAttachs inboundAttachs = new TmsInboundQrcodeAttachs();
            inboundAttachs.setPicKey(key);
            inboundAttachs.setGmtCreate(new Date());
            inboundAttachs.setGmtUpdate(new Date());
            inboundAttachs.setInboundId(wmsInboundOrder.getOdId());
            tmsInboundQrcodeAttachsMapper.insertSelective(inboundAttachs);
            return downloadURL;
        } catch (Exception e) {
            throw new BusinessException("生成二维码图片异常!" + e.getMessage());
        } finally {
            if (byteArrayOutputStream != null) {
                try {
                    byteArrayOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 保存信息到商品库位表
     *
     * @param bo                   参数封装
     * @param wmsInboundAllocation 库位信息
     * @param warehouse            仓库信息
     * @param wmsInboundOrder      订单信息
     * @param wmsInventory         库存
     */
    private void saveInventoryLocation(WmsInboundConfirmBO bo, WmsInboundAllocation wmsInboundAllocation, WmsWarehouse warehouse, WmsInboundOrder wmsInboundOrder, WmsInventory wmsInventory) {
        WmsInventoryLocation inventoryLocation = new WmsInventoryLocation();
        if (wmsInventory != null) {
            inventoryLocation.setInvlocInvId(wmsInventory.getInvId());
        }
        inventoryLocation.setGmtCreate(new Date());
        inventoryLocation.setGmtUpdate(new Date());
        inventoryLocation.setCreateUserId(bo.getUserId());
        inventoryLocation.setModifyUserId(bo.getUserId());
        inventoryLocation.setIsDeleted(DeleteFlagEnum.NORMAL.getValue());
        inventoryLocation.setInvlocCustomerCode(wmsInboundOrder.getOdCustomerCode());
        inventoryLocation.setInvlocCustomerName(wmsInboundOrder.getOdCustomerName());
        if (wmsInboundOrder.getOdId() != null) {
            inventoryLocation.setInvlocOdId(wmsInboundOrder.getOdId());
        }
        inventoryLocation.setInvlocVin(bo.getVin());
        inventoryLocation.setInvlocLocCode(wmsInboundAllocation.getAlSourceLocCode());
        inventoryLocation.setInvlocLocName(wmsInboundAllocation.getAlSourceLocName());
        if (StringUtils.isNotBlank(wmsInboundAllocation.getAlSourceLocId())) {
            inventoryLocation.setInvlocLocId(Long.parseLong(wmsInboundAllocation.getAlSourceLocId()));
        }
        inventoryLocation.setInvlocZoneCode(wmsInboundAllocation.getAlSourceZoneCode());
        inventoryLocation.setInvlocZoneName(wmsInboundAllocation.getAlSourceZoneName());
        if (StringUtils.isNotBlank(wmsInboundAllocation.getAlSourceZoneId())) {
            inventoryLocation.setInvlocZoneId(Long.parseLong(wmsInboundAllocation.getAlSourceZoneId()));
        }
        if (StringUtils.isNotBlank(wmsInboundAllocation.getAlWhId())) {
            inventoryLocation.setInvlocWhId(Long.parseLong(wmsInboundAllocation.getAlWhId()));
        }
        inventoryLocation.setInvlocWhCode(warehouse.getWhCode());
        inventoryLocation.setInvlocWhName(warehouse.getWhName());
        inventoryLocation.setInvlocWhType(warehouse.getWhType());
        //bugfix 2018-2-27 调整库存的批次号以入库的时间为依据,同一天入库的为一批;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        inventoryLocation.setInvlocLot("BTN" + sdf.format(new Date()) + "0001");//批次号
        inventoryLocation.setStatus(InventoryLocationStatusEnum.NORMAL_10.getCode());//正常状态
        wmsInventoryLocationMapper.insertSelective(inventoryLocation);
    }

    /**
     * 保存信息到库存表
     *
     * @param bo              参数
     * @param orderDetail     订单明细
     * @param wmsInboundOrder 订单
     * @return 返回值
     */
    private WmsInventory saveInventory(WmsInboundConfirmBO bo, WmsInboundOrderDetail orderDetail,
                                       WmsInboundOrder wmsInboundOrder, WmsWarehouse warehouse) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        WmsInventory wmsInventory = new WmsInventory();
        wmsInventory.setGmtCreate(new Date());
        wmsInventory.setGmtUpdate(new Date());
        wmsInventory.setCreateUserId(bo.getUserId());
        wmsInventory.setModifyUserId(bo.getUserId());
        wmsInventory.setIsDeleted(DeleteFlagEnum.NORMAL.getValue());
        wmsInventory.setInvCustomerName(wmsInboundOrder.getOdCustomerName());
        wmsInventory.setInvCustomerCode(wmsInboundOrder.getOdCustomerCode());
        wmsInventory.setInvVehicleSpecName(orderDetail.getOddVehicleSpecName());
        wmsInventory.setInvVehicleSpecCode(orderDetail.getOddVehicleSpecCode());
        wmsInventory.setInvVehicleSpecDesc(orderDetail.getOddVehicleSpecDesc());
        //bugfix 2018-2-27 调整库存的批次号以入库的时间为依据,同一天入库的为一批;
        wmsInventory.setInvBatchNo("BTN" + sdf.format(new Date()) + "0001");// 批次号
        wmsInventory.setInvColor(orderDetail.getOddCarColour());//颜色
        String oddMaterialCode = orderDetail.getOddMaterialCode();
        wmsInventory.setInvMaterialCode(StringUtils.isNotBlank(oddMaterialCode) ?
                oddMaterialCode : "");//增加库存的物料编码
        wmsInventory.setInvMaterialName(StringUtils.isNotBlank(orderDetail.getOddMaterialName()) ?
                orderDetail.getOddMaterialName() : "");//增加库存的物料名称
        wmsInventory.setInvCarColourCode(StringUtils.isBlank(orderDetail.getOddCarColourCode()) ?
                (StringUtils.isBlank(oddMaterialCode) ? "" : oddMaterialCode.substring(oddMaterialCode.length() - 2, oddMaterialCode.length() - 1))
                : orderDetail.getOddCarColourCode());//增加库存颜色编码

        if (warehouse != null) {
            wmsInventory.setInvWhCode(warehouse.getWhCode());
            wmsInventory.setInvWhName(warehouse.getWhName());
        }
        wmsInventoryMapper.insertSelective(wmsInventory);
        return wmsInventory;
    }


    /**
     * 君马库app入库确认 --hs
     *
     * @param bo 参数封装
     * @return 返回值
     * @throws Exception 抛出异常
     */
    @Override
    public TmsInboundMoveCarBO saveWareHousingConfirm(WmsInboundConfirmBO bo) throws Exception {
        logger.info("TmsInboundServiceImpl.saveWareHousingConfirm params:{}", bo);
        if (Objects.equals(bo, null)) {
            throw new BusinessException("入库确认信息不能为空!");
        }
        if (StringUtils.isBlank(bo.getVin())) {
            throw new BusinessException("车架号不能为空!");
        }
        if (Objects.equals(bo.getUserId(), null)) {
            throw new BusinessException("入库确认用户Id不能为空!");
        }
        if (Objects.equals(bo.getWarehousePos(), null) || StringUtils.isBlank(bo.getWarehousePos())) {
            throw new BusinessException("入库确认库位信息不能为空!");
        }

        SysUser sysUser = sysUserMapper.selectByPrimaryKey(Integer.valueOf(bo.getUserId()));

        // 订单分配的库位--君马重复入库的进行入库确认操作过滤掉之前已经出库的车架号
        WmsInboundAllocationExample allocationExample = new WmsInboundAllocationExample();
        allocationExample.createCriteria().andAlVinEqualTo(bo.getVin())
                .andIsDeletedNotEqualTo(DeleteFlagEnum.DELETED.getValue());
        List<WmsInboundAllocation> wmsInboundAllocations = wmsInboundAllocationMapper.selectByExample(allocationExample);

        if (CollectionUtils.isEmpty(wmsInboundAllocations)) {
            throw new BusinessException("请进行扫描分配库位!");
        }

        WmsInboundAllocation wmsInboundAllocation = wmsInboundAllocations.get(0);
        if (Objects.equals(wmsInboundAllocation.getAlStatus(),
                WmsInboundAllocationStatusEnum.INBOUND_STATUS.getValue())) {
            throw new BusinessException("该车辆已经入库,无需重复操作!");
        }

        if (!Objects.equals(wmsInboundAllocation.getAlSourceLocCode(), bo.getWarehousePos().trim())) {
            throw new BusinessException("输入库位信息不正确,请确认!");
        }

        // 订单分配的仓库信息
        WmsWarehouseExample warehouseExample = new WmsWarehouseExample();
        WmsWarehouseExample.Criteria warehouseExampleCriteria = warehouseExample.createCriteria();
        warehouseExampleCriteria.andWhIdEqualTo(Long.parseLong(wmsInboundAllocation.getAlWhId()));
        byte del = DeleteFlagEnum.DELETED.getValue();
        warehouseExampleCriteria.andIsDeletedNotEqualTo(del);
        List<WmsWarehouse> wmsWarehouses = wmswarehousemapper.selectByExample(warehouseExample);

        if (CollectionUtils.isEmpty(wmsWarehouses)) {
            throw new BusinessException("库位未查询到对应仓库信息");
        }

        WmsWarehouse warehouse = wmsWarehouses.get(0);

        //入库单及明细--为了避免借车重复出入库 关联订单id 状态为未出库
        WmsInboundOrderDetailExample wmsinboundorderdetailexample = new WmsInboundOrderDetailExample();
        WmsInboundOrderDetailExample.Criteria criteria = wmsinboundorderdetailexample.createCriteria();
        criteria.andOddVinEqualTo(bo.getVin());
        criteria.andIsDeletedNotEqualTo(del);
        wmsinboundorderdetailexample.setOrderByClause(" gmt_create desc");
        List<WmsInboundOrderDetail> wmsInboundOrderDetails = wmsInboundOrderDetailMapper
                .selectByExample(wmsinboundorderdetailexample);
        if (CollectionUtils.isEmpty(wmsInboundOrderDetails)) {
            throw new BusinessException("未查询到对应的入库订单信息");
        }

        WmsInboundOrderDetail orderDetail = wmsInboundOrderDetails.get(0);

        WmsInboundOrderExample orderExample = new WmsInboundOrderExample();
        WmsInboundOrderExample.Criteria orderExampleCriteria = orderExample.createCriteria();
        orderExampleCriteria.andIsDeletedNotEqualTo(del);
        orderExampleCriteria.andOdIdEqualTo(orderDetail.getOddOdId());
        List<WmsInboundOrder> wmsInboundOrders = wmsInboundOrderMapper.selectByExample(orderExample);

        if (CollectionUtils.isEmpty(wmsInboundOrders)) {
            throw new BusinessException("未查询到对应的入库订单信息");
        }

        WmsInboundOrder wmsInboundOrder = wmsInboundOrders.get(0);

        // 确认入库保存库存信息到商品库存表然后
        WmsInventory wmsInventory = saveInventory(bo, orderDetail, wmsInboundOrder, warehouse);

        // 同步信息到库存商品库区库位表中
        saveInventoryLocation(bo, wmsInboundAllocation, warehouse, wmsInboundOrder, wmsInventory);

        // 修改分配订单到库区库位表状态为已入库
        wmsInboundAllocation.setAlStatus(WmsInboundAllocationStatusEnum.INBOUND_STATUS.getValue());
        wmsInboundAllocationMapper.updateByPrimaryKeySelective(wmsInboundAllocation);

        // 设置订单表为已入库
        wmsInboundOrder.setConfirmInboundUserId(Integer.valueOf(bo.getUserId()));
        wmsInboundOrder.setOdStatus(String.valueOf(WmsInboundStatusEnum.WMS_INBOUND_FINISH.getValue()));
        wmsInboundOrder.setGmtUpdate(new Date());
        wmsInboundOrder.setModifyUserId(bo.getUserId());
        wmsInboundOrder.setModifyUserName(sysUser.getName());
        wmsInboundOrderMapper.updateByPrimaryKeySelective(wmsInboundOrder);

        //推送已入库状态到app--君马库
        String jsonStr = "{ \"locName\": " + orderDetail.getOddWhLocCode() + ", \"status\":\"30\", \"statusName\": \"已入库\" }";
        //查询移库司机id
        if (StringUtils.isBlank(wmsInboundOrder.getOdSupplierId())) {
            throw new BusinessException("该车架号:" + orderDetail.getOddVin() + "未绑定移库司机");
        }
        JpushClientUtils.sendToAllAndroid(wmsInboundOrder.getOdSupplierId(), jsonStr, TYPE_INBOUND);

        // 记录到接口表
        WmsOutOfStorage wmsOutOfStorage = new WmsOutOfStorage();
        wmsOutOfStorage.setBldat(new Date());
        UserBO user = userService.findById(Integer.parseInt(bo.getUserId()));
        wmsOutOfStorage.setCreateUserName(user.getUsername());
        wmsOutOfStorage.setGmtCreate(new Date());
        wmsOutOfStorage.setLgort("");//SAP默认
        wmsOutOfStorage.setMatnr(orderDetail.getOddMaterialCode());
        //wmsOutOfStorage.setUmlgo(WhCodeEnum.JM_CS.getValue());//仓库名称
        if (StringUtils.isNotBlank(orderDetail.getOddWhCode())) {
            if (WhCodeEnum.JM_CS.getValue().equals(orderDetail.getOddWhCode())) {
                wmsOutOfStorage.setUmlgo(WebServiceWhcodeEnum.CS01.getValue());
            }
            if (WhCodeEnum.JM_XY.getValue().equals(orderDetail.getOddWhCode())) {
                wmsOutOfStorage.setUmlgo(WebServiceWhcodeEnum.XY01.getValue());
            }
        }
        wmsOutOfStorage.setMblnr("");//调拨入库单号,或者退车单号
        wmsOutOfStorage.setSendStatus(WmsOutOfStorageSendStatus.SEND_INIT.getValue());
        wmsOutOfStorage.setSendStatusSap(SendStatusEnum.SEND_INIT.getValue());
        wmsOutOfStorage.setSernr(bo.getVin());
        wmsOutOfStorage.setUmwrk("");//sap默认
        wmsOutOfStorage.setWerks("");//sap默认
        wmsOutOfStorage.setSerialNo("");
        wmsOutOfStorage.setZaction(WmsOutOfStorageAction.ACTION_INBOUND.getValue());
        wmsOutOfStorage.setZtflag(wmsInboundOrder.getOdIsSpecial());
        wmsOutOfStorage.setZtype(wmsInboundOrder.getOdBusinessType());
        if (StringUtils.isNotBlank(wmsInboundOrder.getOdBusinessType())) {
            if (WmsOutOfStorageType.ZTYPE_INBOUND_Z9.getValue().equals(wmsInboundOrder.getOdBusinessType())) {
                wmsOutOfStorage.setMblnr(wmsInboundOrder.getOdDispatchNo());//退车类型对应借车单单号
            } else if (wmsInboundOrder.getOdBusinessType().equals(WmsOutOfStorageType.ZTYPE_INBOUND_Z2.getValue())) {
                //调拨入库 查询对应的备料计划的车架号并且该车架号的对应类为调拨
                //WmsPreparationPlanExtMapper.selectDispatchOrderByVin(orderDetail.getOddVin(), del);
                wmsOutOfStorage.setMblnr(wmsInboundOrder.getOdDispatchNo());
            }
        }
        wmsOutOfStorageMapper.insert(wmsOutOfStorage);

        // 入库信息同步到DCS /SAP
        TmsInboundMoveCarBO moveCarBO = new TmsInboundMoveCarBO();
        TmsInboundQrcodeAttachsExample attachsExample = new TmsInboundQrcodeAttachsExample();
        TmsInboundQrcodeAttachsExample.Criteria attachsExampleCriteria = attachsExample.createCriteria();
        attachsExampleCriteria.andDelFlagNotEqualTo(false);
        attachsExampleCriteria.andInboundIdEqualTo(wmsInboundOrder.getOdId());
        List<TmsInboundQrcodeAttachs> tmsInboundQrcodeAttachs = tmsInboundQrcodeAttachsMapper
                .selectByExample(attachsExample);
        if (CollectionUtils.isNotEmpty(tmsInboundQrcodeAttachs)) {
            String downloadURL = QiniuUtil.generateDownloadURL(QiniuConstant.QINIU_DOWNLOAD_ADDRESS,
                    tmsInboundQrcodeAttachs.get(0).getPicKey(), "", null, null);
            moveCarBO.setPicUrl(downloadURL);
        }
        moveCarBO.setWarhousingDriverId(bo.getUserId());
        moveCarBO.setVin(bo.getVin());
        moveCarBO.setInboundStatusText(WmsInboundInventoryEnum.MOVEMENT.getText());
        moveCarBO.setInboundStatusValue(WmsInboundInventoryEnum.MOVEMENT.getValue());
        return moveCarBO;
    }

    /**
     * 查询所有的未移车的列表，并过滤掉不能进行移车申请的数据
     * <p>
     * 2018-1-26 重庆库
     * </p>
     *
     * @param whcode 仓库code
     * @return 返回值
     * @throws Exception 抛出异常
     */
    @Override
    public List<WmsInboundNotMoveCarDTO> getNotMoveCarList(String whcode, PageVo vo) throws Exception {
        logger.info("TmsInboundServiceImpl.getNotMoveCarList params:{},{}", whcode, vo);
        if (StringUtils.isBlank(whcode)) {
            throw new BusinessException("传入仓库code为空!");
        }
        if (Objects.equals(vo, null)) {
            throw new BusinessException("分页参数不能为空");
        }
        List<WmsInboundNotMoveCarDTO> notMoveCarDTOS = null;
        if (WhCodeEnum.JM_CS.getValue().equals(whcode) || WhCodeEnum.JM_XY.getValue().equals(whcode)) {
            byte del = DeleteFlagEnum.DELETED.getValue();
            int confirmExcp = TmsInspectStatusEnum.WAYBILL_CONFIRM_EXCP.getValue();
            int qualifyValue = TmsInspectStatusEnum.WAYBILL_QUALIFY.getValue();
            int createValue = WmsInboundStatusEnum.WMS_INBOUND_CREATE.getValue();
            String missCode = WmsInspectExcpTypeEnum.TYPE_MISS.getCode();
            notMoveCarDTOS = wmsInboundInspectExpandMapper.selectNotMoveCarListForJM(whcode, confirmExcp, qualifyValue, del, vo, createValue, missCode);
        }
        if (WhCodeEnum.UNLCN_XN_CQ.getValue().equals(whcode)) {
            Map<String, Object> paramMap = Maps.newHashMap();
            paramMap.put("notDel", DeleteFlagEnum.NORMAL.getValue());
            paramMap.put("whCode", whcode);
            paramMap.put("createValue", WmsInboundStatusEnum.WMS_INBOUND_CREATE.getValue());
            paramMap.put("confirmExcp", TmsInspectStatusEnum.WAYBILL_CONFIRM_EXCP.getValue());
            paramMap.put("qualifyValue", TmsInspectStatusEnum.WAYBILL_QUALIFY.getValue());
            paramMap.put("orderBy", "id desc");
            paramMap.put("start", vo.getStartIndex());
            paramMap.put("end", vo.getPageSize());
            notMoveCarDTOS = wmsInboundInspectExpandMapper.selectNotMoveCarListForCQ(paramMap);

        }
        if (CollectionUtils.isEmpty(notMoveCarDTOS)) {
            throw new BusinessException("未查询到对应的数据");
        }
        notMoveCarDTOS.forEach(v -> {
            if (Objects.equals(v.getInspectStatus(), TmsInspectStatusEnum.WAYBILL_QUALIFY.getValue())) {
                v.setInspectStatusText(TmsInspectStatusEnum.WAYBILL_QUALIFY.getText());
            }
            if (Objects.equals(v.getInspectStatus(), TmsInspectStatusEnum.WAYBILL_CONFIRM_EXCP.getValue())) {
                v.setInspectStatusText(TmsInspectStatusEnum.WAYBILL_EXCP.getText());
            }
        });
        return notMoveCarDTOS;
    }

    /**
     * <p>
     * 2018-1-30 新需求:新增定时任务从tms抓取入库信息;
     * 2018-4-18 针对入库通知单重设计数据表,此方法过时新方法 {@link TmsInboundServiceImpl#fetchInboundOrderBySchedule}
     * </p>
     */
    @Override
    @Deprecated
    public void fetchInboundOrderByScheduleOld() {
        logger.info("TmsInboundServiceImpl.fetchInboundOrderByScheduleOld param:");
        //获取时间戳
        Map<String, Object> paramMap = Maps.newHashMap();
        paramMap.put("createType", "HTTP");
        paramMap.put("notDel", DeleteFlagEnum.NORMAL.getValue());
        paramMap.put("whCode", WhCodeEnum.UNLCN_XN_CQ.getValue());
        paramMap.put("modifyType", "REST");
        paramMap.put("orderBy", "id desc");
        paramMap.put("start", 0);
        paramMap.put("end", 1);
        List<WmsTmsOrder> data = wmsTmsOrderExtMapper.selectLastHTTPTimeStampByParam(paramMap);
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String ts;
        if (CollectionUtils.isEmpty(data)) {
            Calendar calendar = new GregorianCalendar();
            calendar.setTime(date);
            calendar.add(Calendar.DAY_OF_YEAR, -60);
            ts = sdf.format(calendar.getTime());
        } else {
            ts = sdf.format(data.get(0).getGmtCreate());
        }
        //调用tms获取定时数据
        String result = callTms(ts);
        //记录日志
        Runnable runnable = () -> {
            WmsTmsLogWithBLOBs log = new WmsTmsLogWithBLOBs();
            log.setUrl("TmsInboundServiceImpl.fetchInboundOrderByScheduleOld");
            log.setSendType(WmsGateControllerTypeEnum.GATE_OUT.getCode());
            log.setGmtUpdate(date);
            log.setGmtCreate(date);
            log.setBody(result);
            log.setParam(ts);
            wmsTmsLogMapper.insertSelective(log);
        };
        new Thread(runnable).start();

        if (StringUtils.isNotBlank(result)) {
            //如果本地存在改订单号已经更新的数据就跳过
            JSONObject jsonObject = JSONObject.parseObject(result);
            String records = jsonObject.getString("records");
            Boolean success = jsonObject.getBoolean("success");
            String message = jsonObject.getString("message");
            if (!success) {
                logger.error("TmsInboundServiceImpl.callTms bussinessException:", message);
            } else {
                //定时抓取的数据都插入到接口表中-->在进行模糊查询车架号的时候  需要判断类型 获取数据的流程-->order-->rest方式修改-->http
                //后续同步接口表数据到业务order表中的时候需要绑定接口表的id 便于数据核实
                List<TmsInboundInspectBO> boList = JSONObject.parseArray(records, TmsInboundInspectBO.class);
                ArrayList<WmsTmsOrder> orders = Lists.newArrayList();
                boList.stream().filter(v -> (!Objects.equals(v, null)
                        && (StringUtils.isNotBlank(v.getDest())
                        && WhCodeEnum.UNLCN_XN_CQ.getText().equals(v.getDest()))))
                        .forEach(bo -> {
                            WmsTmsOrder tmsOrder = new WmsTmsOrder();
                            tmsOrder.setCreateName("HTTP");
                            tmsOrder.setModifyName("HTTP");
                            tmsOrder.setFactoryWhno(bo.getFactory_whno());
                            tmsOrder.setFetchTimestamp(Long.valueOf(DateUtils.getStringFromDate(new Date(), DateUtils.FORMAT_DATETIME_NO_SEPARATOR)));
                            tmsOrder.setGmtCreate(date);
                            tmsOrder.setGmtUpdate(date);
                            tmsOrder.setIsDeleted(DeleteFlagEnum.NORMAL.getValue());
                            tmsOrder.setOdCustomerOrderNo(bo.getCustOrderno());
                            tmsOrder.setOdCustomerName(bo.getCustomer());
                            tmsOrder.setOdDest(bo.getDest());
                            tmsOrder.setOdOrigin(bo.getOrigin());
                            tmsOrder.setOdStyleId(Long.valueOf(bo.getStyleId()));
                            tmsOrder.setOddVin(bo.getVin());
                            tmsOrder.setOddStockTransfer(bo.getStocktransfer());
                            tmsOrder.setOdWaybillNo(bo.getCustShipno());
                            tmsOrder.setOdOrderno(bo.getOrderno());
                            tmsOrder.setOddVehicleSpecDesc(bo.getStyleDesc());
                            tmsOrder.setOddVehicleSpecName(bo.getStyle());
                            tmsOrder.setSendBusinessFlag((byte) SendBusinessFlagEnum.SEND_N.getValue());
                            tmsOrder.setOdWhCode(WhCodeEnum.UNLCN_XN_CQ.getValue());
                            tmsOrder.setOdWhName(WhCodeEnum.UNLCN_XN_CQ.getText());
                            orders.add(tmsOrder);
                            //wmsTmsOrderMapper.insertSelective(tmsOrder);
                        });
                wmsTmsOrderExtMapper.insertDataBatch(orders);
            }
        }
    }

    @Autowired
    private WmsWarehouseNoticeExtMapper wmsWarehouseNoticeExtMapper;


    /**
     * <p>
     * 2018-1-30 新需求:新增定时任务从tms抓取入库信息;
     * 2018-4-18 针对入库通知单重设计数据表,此方法新方法
     * </p>
     */
    @Override
    public void fetchInboundOrderBySchedule() {
        logger.info("TmsInboundServiceImpl.fetchInboundOrderBySchedule param:");
        //获取时间戳-head表
        Map<String, Object> paramMap = Maps.newHashMap();
        paramMap.put("createType", WmsSysSourceEnum.HTTP.getValue());
        paramMap.put("notDel", DeleteFlagEnum.NORMAL.getValue());
        paramMap.put("whCode", WhCodeEnum.UNLCN_XN_CQ.getValue());
        paramMap.put("modifyType", WmsSysSourceEnum.REST.getValue());
        paramMap.put("orderBy", "wnh_id desc");
        paramMap.put("start", 0);
        paramMap.put("end", 1);
        List<WmsWarehouseNoticeHeadDTO> data = wmsWarehouseNoticeExtMapper.selectLastHTTPTimeStampByParam(paramMap);
        //List<WmsTmsOrder> data = wmsTmsOrderExtMapper.selectLastHTTPTimeStampByParam(paramMap);
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String ts;
        if (CollectionUtils.isEmpty(data)) {
            Calendar calendar = new GregorianCalendar();
            calendar.setTime(date);
            calendar.add(Calendar.DAY_OF_YEAR, -60);
            ts = sdf.format(calendar.getTime());
        } else {
            ts = sdf.format(data.get(0).getWnhCreate());
        }
        String finalTs = ts;
        //调用tms获取定时数据
        String result = callTms(ts);
        //记录日志
        Runnable runnable = () -> {
            WmsTmsLogWithBLOBs log = new WmsTmsLogWithBLOBs();
            log.setUrl("TmsInboundServiceImpl.fetchInboundOrderBySchedule");
            log.setSendType(WmsGateControllerTypeEnum.GATE_OUT.getCode());
            log.setGmtUpdate(date);
            log.setGmtCreate(date);
            log.setBody(result);
            log.setParam(finalTs);
            wmsTmsLogMapper.insertSelective(log);
        };
        new Thread(runnable).start();

        if (StringUtils.isNotBlank(result)) {
            //如果本地存在改订单号已经更新的数据就跳过
            JSONObject jsonObject = JSONObject.parseObject(result);
            String records = jsonObject.getString("records");
            Boolean success = jsonObject.getBoolean("success");
            String message = jsonObject.getString("message");
            if (!success) {
                logger.error("TmsInboundServiceImpl.callTms bussinessException:", message);
            } else {
                //定时抓取的数据都插入到接口表中-->在进行模糊查询车架号的时候  需要判断类型 获取数据的流程-->order-->rest方式修改-->http
                //后续同步接口表数据到业务order表中的时候需要绑定接口表的id 便于数据核实
                List<TmsInboundInspectBO> boList = JSONObject.parseArray(records, TmsInboundInspectBO.class);
                ArrayList<WmsWarehouseNoticeHead> heads = Lists.newArrayList();
                ArrayList<WmsWarehouseNoticeDetail> details = Lists.newArrayList();
                SnowflakeIdWorker idWorker = new SnowflakeIdWorker(31L, 31L);
                boList.stream().filter(v -> (!Objects.equals(v, null)
                        && (StringUtils.isNotBlank(v.getDest())
                        && WhCodeEnum.UNLCN_XN_CQ.getText().equals(v.getDest()))))
                        .forEach(bo -> {
                            WmsWarehouseNoticeHead head = new WmsWarehouseNoticeHead();
                            WmsWarehouseNoticeDetail detail = new WmsWarehouseNoticeDetail();
                            //设置头表的head ID
                            long headId = idWorker.nextId();
                            head.setWnhId(headId);
                            head.setWnhCustomerCode(WmsCustomerEnum.CQ_JL.getCode());
                            head.setWnhCustomerName(bo.getCustomer());
                            head.setWnhCustomerOrderNo(bo.getCustOrderno());
                            head.setWnhCustomerWaybillNo(bo.getCustShipno());
                            head.setWnhUnlcnOrderNo(bo.getOrderno());
                            head.setWnhOriginName(bo.getOrigin());
                            head.setWnhDestinationName(bo.getDest());
                            head.setWnhInboundNum(1);
                            head.setWnhCreate(new Date());
                            head.setWnhUpdate(new Date());
                            head.setWnhCreateUserName(WmsSysSourceEnum.HTTP.getValue());
                            head.setWnhUpdateUserName(WmsSysSourceEnum.HTTP.getValue());
                            Long timestamp = Long.valueOf(DateUtils.getStringFromDate(new Date(), DateUtils.FORMAT_DATETIME_NO_SEPARATOR));
                            head.setWnhDataTimestamp(timestamp);
                            head.setWnhSysSource(WmsSysSourceEnum.HTTP.getValue());
                            head.setWnhBusinessStatus(WmsBusinessStatusEnum.WNH_NOT_INBOUND.getCode());
                            head.setWnhDataStatus(String.valueOf(DeleteFlagEnum.NORMAL.getValue()));
                            head.setWnhWarehouseCode(WhCodeEnum.UNLCN_XN_CQ.getValue());
                            //details
                            detail.setWndHeadId(head.getWnhId());
                            detail.setWndVin(bo.getVin());
                            detail.setWndVehicleId(Long.valueOf(bo.getStyleId()));
                            detail.setWndVehicleName(bo.getStyle());
                            detail.setWndVehicleDesc(bo.getStyleDesc());
                            detail.setWndCustomerWhno(bo.getFactory_whno());
                            detail.setWndCreate(new Date());
                            detail.setWndUpdate(new Date());
                            detail.setWndCreateUserName(WmsSysSourceEnum.HTTP.getValue());
                            detail.setWndUpdateUserName(WmsSysSourceEnum.HTTP.getValue());
                            detail.setWndBusinessStatus(WmsBusinessStatusEnum.WND_NOT_RECEIVE.getCode());
                            detail.setWndSendBusinessFlag(String.valueOf(SendBusinessFlagEnum.SEND_N.getValue()));
                            detail.setWndDataStatus(String.valueOf(DeleteFlagEnum.NORMAL.getValue()));
                            detail.setWndWarehouseCode(WhCodeEnum.UNLCN_XN_CQ.getValue());
                            detail.setWndBusinessType(InboundOrderBusinessTypeEnum.Z1.getCode());
                            if (WmsInboundOrderStockTransferEnum.STOCK_NORMAL.getCode().equals(bo.getStocktransfer())) {
                                detail.setWndTransferFlag(WmsInboundOrderStockTransferEnum.STOCK_NORMAL.getCode());
                            } else {
                                detail.setWndTransferFlag(WmsInboundOrderStockTransferEnum.STOCK_NOTCQ.getCode());
                            }
                            details.add(detail);
                            heads.add(head);
                        });
                wmsWarehouseNoticeExtMapper.insertHeadBatch(heads);
                wmsWarehouseNoticeExtMapper.insertDetailBatch(details);
            }
        }
    }


    /**
     * 调用 tms 的接口(抓取验车单信息,或者生成验车合格的状态)
     *
     * @param timestamp 定时调取tms获取入库信息的时间戳
     * @return 返回值
     */
    private String callTms(String timestamp) {
        // 构建URL
        String url = propertyUrl;
        Integer time = Integer.parseInt(propertyTime);
        String encode_key = propertyKey;
        Map<String, Object> map = new HashMap<>();
        Map<String, Object> headerMap = new HashMap<>();
        headerMap.put("encode-key", encode_key);
        url = url + "/mSearchVINOrder.jspx";
        map.put("timestamp", timestamp);
        String result = null;
        try {
            result = HttpRequestUtil.sendHttpPost(url, headerMap, map, time);
        } catch (Exception e) {
            logger.error("TmsInboundServiceImpl.callTms error:", e);
        }

        return result;
    }


}
